﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;

public partial class InspectionSetting : ExtBaseRpt
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!X.IsAjaxRequest)
        {}
        if (Session["UserID"] == null)
        {
            ShowBox("用户登入超时请求重新登入");
        }
    }

    //protected void LoadDataRun(object sender, EventArgs e)
    //{
    //    this.ResourceManager1.AddScript("LoadData()");
    //}

    //查询所有巡检数据
    [DirectMethod(Namespace = "CompanyX")]
    public ListModel LoadDataItem(string JsonParams)
    {
        ListModel listM = new ListModel();
        List<InspectionSettingModel> data = new List<InspectionSettingModel>();
        try
        {
            string selQuery = string.Format(@"SELECT 
	ins_id,
	ins_parentCode,
	ins_childCode,
	ins_parentName,
	ins_parentShortName,
	ins_score,
	ins_checkContext,
	ins_checkContextRemark,
	ins_importanceDegree,
	ins_flag
FROM t_inspection_setting
WHERE isRemove=0
ORDER BY ins_parentCode,ins_childCode ");

            DataSet ds = mydb.DM_GetDateSet(selQuery);
            if (ds != null&& ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                System.Data.DataView view = new System.Data.DataView();
                view.Table = dt;
                view.RowFilter = "ins_childCode = '0'";//ins_childCode是dt中的一个字段
                DataTable pTab = view.ToTable();
                for (int i = 0; i < pTab.Rows.Count; i++)
                {
                    InspectionSettingModel model = new InspectionSettingModel();
                    List<ChildModel> lcMod = new List<ChildModel>();
                    string ins_parentCode = pTab.Rows[i]["ins_parentCode"].ToString();
                    model.pId = Convert.ToInt32(pTab.Rows[i]["ins_id"].ToString());
                    model.pCode = ins_parentCode;
                    model.lName = pTab.Rows[i]["ins_parentName"].ToString();
                    model.sName = pTab.Rows[i]["ins_parentShortName"].ToString();
                    model.pScore = Convert.ToDecimal(pTab.Rows[i]["ins_score"].ToString());
                    
                    view.RowFilter = "ins_childCode <> '0' and ins_parentCode = '"+ ins_parentCode + "'";
                    DataTable cTab = view.ToTable();
                    for (int j = 0; j < cTab.Rows.Count; j++)
                    {
                        ChildModel cMod = new ChildModel();
                        cMod.cId = Convert.ToInt32(cTab.Rows[j]["ins_id"].ToString());
                        cMod.Des = cTab.Rows[j]["ins_checkContext"].ToString();
                        cMod.MagDes = cTab.Rows[j]["ins_checkContextRemark"].ToString();
                        cMod.Score = Convert.ToDecimal(cTab.Rows[j]["ins_score"].ToString());
                        cMod.Degree = Convert.ToInt32(cTab.Rows[j]["ins_importanceDegree"].ToString());
                        int State = 0;
                        if (Convert.ToBoolean(cTab.Rows[j]["ins_flag"].ToString()) == true)
                        {
                            State = 1;
                        }
                        cMod.State = State;
                        lcMod.Add(cMod);
                    }
                    model.data = lcMod;
                    data.Add(model);
                }
            }
            else
            {
                InspectionSettingModel model = new InspectionSettingModel();
                data.Add(model);
            }
        }
        catch (Exception ex)
        {
            ShowBox(ex.Message);
            InspectionSettingModel model = new InspectionSettingModel();
            data.Add(model);
        }
        listM.list = data;
        return listM;
    }

    //创建巡检类别
    [DirectMethod(Namespace = "CompanyX")]
    public int AddFoundRun(string JsonParams)
    {
        int Num = 0;
        try
        {
            //反序列化为ShopImg对象
            var model = JSON.Deserialize<InspectionSettingModel>(JsonParams);
            if (string.IsNullOrEmpty(model.lName))
            {
                return 0;
            }
            else if (string.IsNullOrEmpty(model.sName))
            {
                return 0;
            }
            else if (model.pScore <= 0)
            {
                return 0;
            }
            else
            {
                string ins_parentCode = GetParentCode();
                if (string.IsNullOrEmpty(ins_parentCode))
                {
                    return 0;
                }
                else
                {
                    if (Session["UserID"] == null)
                    {
                        return 0;
                    }
                    else
                    {
                        string[] insertSqlList = new string[model.data.Count + 1];
                        int creator = Convert.ToInt32(this.UserId);
                        string pSql = string.Format(@"INSERT INTO t_inspection_setting([ins_parentCode]
           ,[ins_childCode]
           ,[ins_parentName]
           ,[ins_parentShortName]
           ,[ins_checkContext]
           ,[ins_checkContextRemark]
           ,[ins_score]
           ,[ins_importanceDegree]
           ,[ins_flag]
           ,[isRemove]
           ,[create_date]
           ,[creator])VALUES('{0}','0','{1}','{2}','','',{3},1,1,0,GETDATE(),{4}) ", ins_parentCode, model.lName, model.sName, model.pScore, creator);
                        insertSqlList[0] = pSql;
                        
                        for (int i = 0; i < model.data.Count; i++)
                        {
                            int intNum = i + 1;
                            string ins_childCode = ins_parentCode + "C_" + intNum.ToString().PadLeft(3, '0');
                            string cSql = string.Format(@"INSERT INTO t_inspection_setting([ins_parentCode]
           ,[ins_childCode]
           ,[ins_parentName]
           ,[ins_parentShortName]
           ,[ins_checkContext]
           ,[ins_checkContextRemark]
           ,[ins_score]
           ,[ins_importanceDegree]
           ,[ins_flag]
           ,[isRemove]
           ,[create_date]
           ,[creator])VALUES('{0}','{1}','{2}','{3}','{4}','{5}',{6},{7},{8},0,GETDATE(),{9}) ", ins_parentCode, ins_childCode, model.lName, model.sName, model.data[i].Des,
           model.data[i].MagDes, model.data[i].Score, model.data[i].Degree, model.data[i].State, creator);
                            insertSqlList[intNum] = cSql;
                        }
                        
                        bool bol = mydb.ExecuteNonQueryTran(insertSqlList);
                        if (bol == true)
                        {
                            Num = 1;
                        }
                        else
                        {
                            Num = 0;
                        }
                    }
                }
                
            }
        }
        catch (Exception ex)
        {
            ShowBox(ex.Message);
        }
        return Num;
    }

    //保存巡检类别
    [DirectMethod(Namespace = "CompanyX")]
    public int SevaEditRun(string JsonParams)
    {
        int Num = 0;
        try
        {
            //反序列化为ShopImg对象
            var model = JSON.Deserialize<InspectionSettingModel>(JsonParams);
            if (model.pId <= 0)
            {
                return 0;
            }
            else if (string.IsNullOrEmpty(model.pCode))
            {
                return 0;
            }
            else if (string.IsNullOrEmpty(model.lName))
            {
                return 0;
            }
            else if (string.IsNullOrEmpty(model.sName))
            {
                return 0;
            }
            else if (model.pScore <= 0)
            {
                return 0;
            }
            else
            {
                //=======================================================
                int IsIdCode = IsParentCode(model.pId, model.pCode);
                if (IsIdCode == 1)
                {
                    if (Session["UserID"] == null)
                    {
                        return 0;
                    }
                    else
                    {
                        string[] insertSqlList = new string[model.data.Count + 1];
                        int creator = Convert.ToInt32(this.UserId);
                        string pSql = string.Format(@"UPDATE t_inspection_setting
   SET [ins_parentName] = '{0}'
      ,[ins_parentShortName] = '{1}'
      ,[ins_score] = {2}
      ,[create_date] = GETDATE()
      ,[creator] = {3}
WHERE ins_id={4} AND ins_parentCode='{5}' ", model.lName, model.sName, model.pScore, creator, model.pId, model.pCode);

                        insertSqlList[0] = pSql;

                        string MaxChildCode = GetChildCode(model.pCode);
                        if (string.IsNullOrEmpty(MaxChildCode))
                        {
                            return 0;
                        }
                        else
                        {
                            int intNum = 1;
                            for (int i = 0; i < model.data.Count; i++)
                            {
                                if (model.data[i].cId == 0)
                                {
                                    string ins_childCode = string.Empty;
                                    if (intNum == 1)
                                    {
                                        ins_childCode = MaxChildCode;
                                    }
                                    else
                                    {
                                        //生成新增子节点编号
                                        var index = Convert.ToInt32(MaxChildCode.Split('_')[1].ToString()) + intNum;
                                        ins_childCode = model.pCode + "C_" + index.ToString().PadLeft(3, '0');
                                    }
                                    string cSql = string.Format(@"INSERT INTO [dbo].[t_inspection_setting]([ins_parentCode]
           ,[ins_childCode]
           ,[ins_parentName]
           ,[ins_parentShortName]
           ,[ins_checkContext]
           ,[ins_checkContextRemark]
           ,[ins_score]
           ,[ins_importanceDegree]
           ,[ins_flag]
           ,[isRemove]
           ,[create_date]
           ,[creator])VALUES('{0}','{1}','{2}','{3}','{4}','{5}',{6},{7},{8},0,GETDATE(),{9}) ", model.pCode, ins_childCode, model.lName, model.sName, model.data[i].Des,
                   model.data[i].MagDes, model.data[i].Score, model.data[i].Degree, model.data[i].State, creator);
                                    insertSqlList[i+1] = cSql;
                                    intNum = intNum + 1;
                                }
                                else
                                {
                                    string cuSql = string.Format(@"UPDATE [dbo].[t_inspection_setting]
   SET [ins_parentName] = '{0}'
      ,[ins_parentShortName] = '{1}'
      ,[ins_checkContext] = '{2}'
      ,[ins_checkContextRemark] = '{3}'
      ,[ins_score] = {4}
      ,[ins_importanceDegree] = {5}
      ,[ins_flag] = {6}
      ,[create_date] = GETDATE()
      ,[creator] = {7}
WHERE ins_id={8} AND ins_parentCode='{9}' ", model.lName, model.sName, model.data[i].Des, model.data[i].MagDes, model.data[i].Score, model.data[i].Degree,
model.data[i].State, creator, model.data[i].cId, model.pCode);

                                    insertSqlList[i+1] = cuSql;
                                }
                            }

                            bool bol = mydb.ExecuteNonQueryTran(insertSqlList);
                            if (bol == true)
                            {
                                Num = 1;
                            }
                            else
                            {
                                Num = 0;
                            }
                        }
                    }
                }
                else
                {
                    return 0;
                }
            }
        }
        catch (Exception ex)
        {
            ShowBox(ex.Message);
        }
        return Num;
    }

    //删除单行
    [DirectMethod(Namespace = "CompanyX")]
    public int SevaDelOneRun(string JsonParams)
    {
        int Num = 0;
        try
        {
            //反序列化为ShopImg对象
            var model = JSON.Deserialize<DelOneModel>(JsonParams);
            if (model.pId <= 0)
            {
                return 0;
            }
            else if (model.pScore < 0)
            {
                return 0;
            }
            else
            {
                //=======================================================
                int IsIdCode = IsInsIdFinishDetail(model.cId.ToString());
                if (IsIdCode == 0)
                {
                    if (Session["UserID"] == null)
                    {
                        return 0;
                    }
                    else
                    {
                        string[] insertSqlList = new string[2];
                        string pSql = string.Format(@"UPDATE t_inspection_setting SET [ins_score] = {0} WHERE ins_id={1} ", model.pScore, model.pId);
                        insertSqlList[0] = pSql;
                        string cSql = string.Format(@"UPDATE t_inspection_setting SET [isRemove] = 1 WHERE ins_id={0} ", model.cId);
                        insertSqlList[1] = cSql;
                        bool bol = mydb.ExecuteNonQueryTran(insertSqlList);
                        if (bol == true)
                        {
                            Num = 1;
                        }
                        else
                        {
                            Num = 0;
                        }
                    }
                }
                else if (IsIdCode == -1)
                {
                    return 0;
                }
                else
                {
                    return 2; //数据项以使用
                }
            }
        }
        catch (Exception ex)
        {
            ShowBox(ex.Message);
        }
        return Num;
    }

    //判断评分子项是否在巡检中
    [DirectMethod(Namespace = "CompanyX")]
    public int IsProgressRun(string JsonParams)
    {
        int Num = 0;
        try
        {
            string sqlQuery = string.Format(@"SELECT TOP 1 ins_id FROM t_inspection_finishDetail AS fd
INNER JOIN t_inspection_finishMaster AS fm
ON fd.tif_id=fm.tif_id AND fm.tif_progress=0
WHERE fm.isRemove=0 AND fd.ins_id IN({0}) ", JsonParams);
            object obj = mydb.DM_GetExecuteScalarObj(sqlQuery);
            if (obj != null && obj.ToString() != "-1")
            {
                //存在
                Num = 1;
            }
            else if (obj == null)
            {
                //不存在
                Num = 0;
            }
            else
            {
                //执行查询语句报错放回空
                Num = -1;
            }
        }
        catch (Exception ex)
        {
            ShowBox(ex.Message);
        }
        return Num;
    }

    //删除巡检类别多行
    [DirectMethod(Namespace = "CompanyX")]
    public int SevaDelRun(string JsonParams)
    {
        int Num = 0;
        try
        {
            if (string.IsNullOrEmpty(JsonParams))
            {
                return 0;
            }
            else
            {
                //=======================================================
                int IsIdCode = IsInsIdFinishDetail(JsonParams);
                if (IsIdCode == 0)
                {
                    if (Session["UserID"] == null)
                    {
                        return 0;
                    }
                    else
                    {
                        string cSql = string.Format(@"UPDATE [dbo].[t_inspection_setting] SET [isRemove] = 1 WHERE ins_id IN ({0}) ", JsonParams);
                        int bol = mydb.DM_ExecuteNonQuery(cSql);
                        if (bol > 0)
                        {
                            Num = 1;
                        }
                        else
                        {
                            Num = 0;
                        }
                    }
                }
                else if (IsIdCode == -1)
                {
                    return 0;
                }
                else
                {
                    return 2; //数据项以使用
                }
            }
        }
        catch (Exception ex)
        {
            ShowBox(ex.Message);
        }
        return Num;
    }

    /// <summary>
    /// 判断父节点的编码是否存在
    /// 1: 存在 0：不存在 -1：执行报错
    /// </summary>
    /// <param name="pId">父节点内码ID</param>
    /// <param name="pCode">父节点编码</param>
    /// <returns></returns>
    public int IsParentCode(int pId, string pCode)
    {
        try
        {
            string sqlQuery = string.Format(@"SELECT TOP 1 ins_childCode FROM t_inspection_setting WHERE ins_id={0} AND ins_parentCode='{1}' ORDER BY ins_childCode DESC ", pId, pCode);
            object obj = mydb.DM_GetExecuteScalarObj(sqlQuery);
            if (obj != null && obj.ToString() != "-1")
            {
                //存在
                return 1;
            }
            else if (obj == null)
            {
                //不存在
                return 0;
            }
            else
            {
                //执行查询语句报错放回空
                return -1;
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }

    /// <summary>
    /// 判断子节点的内码ID是否存在
    /// 1: 存在 0：不存在 -1：执行报错
    /// </summary>
    /// <param name="cId">子节点内码ID</param>
    /// <returns></returns>
    public int IsChildCode(int cId)
    {
        try
        {
            string sqlQuery = string.Format(@"SELECT TOP 1 ins_childCode FROM t_inspection_setting WHERE ins_id={0} ORDER BY ins_childCode DESC ", cId);
            object obj = mydb.DM_GetExecuteScalarObj(sqlQuery);
            if (obj != null && obj.ToString() != "-1")
            {
                //存在
                return 1;
            }
            else if (obj == null)
            {
                //不存在
                return 0;
            }
            else
            {
                //执行查询语句报错放回空
                return -1;
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }

    /// <summary>
    /// 判断巡检类别里面的ID是否存在巡检操作明细表中
    /// 1: 存在 0：不存在 -1：执行报错
    /// </summary>
    /// <param name="IdItem">ID集合：1,2,3,</param>
    /// <returns></returns>
    public int IsInsIdFinishDetail(string IdItem)
    {
        try
        {
            //IdItem = IdItem.Substring(0, IdItem.Length - 1);
            string sqlQuery = string.Format(@"SELECT TOP 1 ins_id FROM [dbo].[t_inspection_finishDetail] WHERE ins_id IN({0}) ", IdItem);
            object obj = mydb.DM_GetExecuteScalarObj(sqlQuery);
            if (obj != null && obj.ToString() != "-1")
            {
                //存在
                return 1;
            }
            else if (obj == null)
            {
                //不存在
                return 0;
            }
            else
            {
                //执行查询语句报错放回空
                return -1;
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }

    /// <summary>
    /// 获取新的巡检类别代码
    /// ParentCode=生成的编码 ParentCode="" 时生成失败
    /// </summary>
    /// <returns></returns>
    public string GetParentCode()
    {
        try
        {
            string ParentCode = string.Empty;
            object obj = mydb.DM_GetExecuteScalarObj("SELECT TOP 1 ins_parentCode FROM t_inspection_setting ORDER BY ins_parentCode DESC ");
            if (obj != null && obj.ToString() != "-1")
            {
                ParentCode = obj.ToString();
                //获取最大编号加1
                var intNum = Convert.ToInt32(ParentCode.Split('-')[1].ToString()) + 1;
                ParentCode = "P-" + intNum.ToString().PadLeft(3, '0');
                return ParentCode;
            }
            else if (obj == null)
            {
                return "P-001";
            }
            else
            {
                //执行查询语句报错放回空
                return "";
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }

    /// <summary>
    /// 根据父节点的内码ID和父节点的编码获取子节点的最大编码数
    /// </summary>
    /// <param name="pCode">父节点编码</param>
    /// <returns></returns>
    public string GetChildCode(string pCode)
    {
        try
        {
            string ChildCode = string.Empty;
            string sqlQuery = string.Format(@"SELECT TOP 1 ins_childCode FROM t_inspection_setting WHERE ins_parentCode='{0}' ORDER BY ins_childCode DESC  ", pCode);
            object obj = mydb.DM_GetExecuteScalarObj(sqlQuery);
            if (obj != null && obj.ToString() != "-1")
            {
                ChildCode = obj.ToString();
                //获取最大编号加1
                var intNum = Convert.ToInt32(ChildCode.Split('_')[1].ToString()) + 1;
                ChildCode = pCode + "C_" + intNum.ToString().PadLeft(3, '0');
                return ChildCode;
            }
            else if (obj == null)
            {
                return pCode + "C_001";//父节点保存值
            }
            else
            {
                //执行查询语句报错放回空
                return "";
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }

    public class ListModel
    {
        public List<InspectionSettingModel> list { get; set; }
    }

    //巡检表设置实体类
    public class InspectionSettingModel
    {
        /// <summary>
        /// 父节点内码ID
        /// </summary>
        public int pId { get; set; }
        /// <summary>
        /// 父节点编码
        /// </summary>
        public string pCode { get; set; }
        /// <summary>
        /// 巡检类别
        /// </summary>
        public string lName { get; set; }
        /// <summary>
        /// 简称
        /// </summary>
        public string sName { get; set; }
        /// <summary>
        /// 分数占比
        /// </summary>
        public decimal pScore { get; set; }

        public List<ChildModel> data { get; set; }
    }

    //巡检表设置子类实体
    public class ChildModel
    {
        /// <summary>
        /// 子节点内码ID
        /// </summary>
        public int cId { get; set; }
        /// <summary>
        /// 检查项目
        /// </summary>
        public string Des { get; set; }
        /// <summary>
        /// 检查项目说明
        /// </summary>
        public string MagDes { get; set; }
        /// <summary>
        /// 分值
        /// </summary>
        public decimal Score { get; set; }
        /// <summary>
        /// 重要程度
        /// </summary>
        public int Degree { get; set; }
        /// <summary>
        /// 是否有效:默认1-有效
        /// </summary>
        public int State { get; set; }
    }

    //删除单行请求参数实体
    public class DelOneModel
    {
        /// <summary>
        /// 父节点内码ID
        /// </summary>
        public int pId { get; set; }
        /// <summary>
        /// 子节点内码ID
        /// </summary>
        public int cId { get; set; }
        /// <summary>
        /// 分数占比
        /// </summary>
        public decimal pScore { get; set; }
    }
}